package es.uc3m.setichat.activity;

import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import es.uc3m.setichat.R;
import es.uc3m.setichat.db.SaveDataContacts;
import es.uc3m.setichat.format.Contacto;
import es.uc3m.setichat.format.ViewContact;
import es.uc3m.setichat.service.SeTIChatService;
import es.uc3m.setichat.service.SeTIChatServiceBinder;
import es.uc3m.setichat.xmlparser.XmlCreate;

/**Clase de la interfaz que lista todos los contactos de nuestra agenda que estan dados de alta en SetiChat*/
public class AddContactsActivity extends ListActivity {
	
	String tokenDb = null;
	private SeTIChatService mService;
	ListActivity context;
	ViewContact viewContact;
	
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.contacts);
        
        context=this;
		
		try{		
			startService(new Intent(AddContactsActivity.this, SeTIChatService.class));
			bindService(new Intent(AddContactsActivity.this, SeTIChatService.class), mConnection, Context.BIND_AUTO_CREATE);

		}catch(Exception e){
			e.printStackTrace();
		}
    }
	
	@Override
	public void onDestroy() {
		Log.d("AddContactsActivity", "onDestroy");
		super.onDestroy();	

		unbindService(mConnection);
	}

	@Override
	protected void onStop() {
		Log.d("AddContactsActivity", "onStop");
		super.onStop();

	}

	@Override
	protected void onResume() {
		Log.d("AddContactsActivity", "onResume");
		super.onResume();		
	}
	
	private ServiceConnection mConnection = new ServiceConnection() {
		
		@Override
		public void onServiceConnected(ComponentName className,	IBinder service) {	
			Log.d("AddContactsActivity", "onServiceConnected");
			mService=SeTIChatServiceBinder.getService();
			//Obtenemos el token de usuario
			tokenDb=SaveDataContacts.selectToken(context);
		
			try {
				String xmlConnection = XmlCreate.connectionMessage(tokenDb, "");		
				mService.sendMessage(xmlConnection);
			} catch (Exception e) {
				e.printStackTrace();
			}				
	
			ArrayList <Contacto> datos = new ArrayList <Contacto> ();

			SaveDataContacts usdbh = new SaveDataContacts(context, SaveDataContacts.DBNAME, null, 1);	
			SQLiteDatabase db = usdbh.getReadableDatabase();
			if(db!=null){
				Cursor cur = db.query("contactos", null, null, null, null, null, null);
				if(cur.getCount()>0){
					while(cur.moveToNext()){
						Contacto auxiliar = new Contacto();
						auxiliar.setMobile(cur.getString(cur.getColumnIndex("mobile")));
						auxiliar.setNick(cur.getString(cur.getColumnIndex("nick")));
						datos.add(auxiliar);
					}				
				}
				cur.close();
				db.close();
			} 
			
			viewContact = new ViewContact (context, datos);
			context.getListView().setAdapter(viewContact);
			context.getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
				
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					Contacto contact = viewContact.getItem(arg2);
					System.out.println("Se abre chat con: "+contact.getNick()+" "+contact.getMobile());
					Intent intent = new Intent(AddContactsActivity.this, ChatActivity.class);
					intent.putExtra("mobile", contact.getMobile());
					
					SaveDataContacts db = new SaveDataContacts(context, SaveDataContacts.DBNAME, null, 1);
					SQLiteDatabase dataBase = db.getReadableDatabase();
					
					if(dataBase!=null){
						Cursor cursor = dataBase.rawQuery("SELECT key FROM usuario WHERE mobile='"+ contact.getMobile() +"'",null);
						//Obtencion en la base de datos del key con el movil, verificamos que no este vacio					
						if(!cursor.moveToFirst()||cursor.getString(0)==null||cursor.getString(0).compareTo("null")==0){
							String xmlPeticionClave;
							try {
								xmlPeticionClave = XmlCreate.keyRequestMessage(tokenDb, "public", contact.getMobile() );
								mService.sendMessage(xmlPeticionClave);
							} catch (Exception e) {
								e.printStackTrace();
							}	
						}
						cursor.close();
						dataBase.close();
					}
					startActivity(intent);
				}
			});
		}
		
		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			Log.d("AddContactsActivity", "onServiceDisconnected");
		}
	};
	
	
	
}
